<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>在光标处插入文字</title>
    <meta content="text/html; charset=UTF-8" http-equiv="content-type">
    <script src="../jquery-1.6.2.min.js" type="text/javascript"></script>
    <link rel="stylesheet" href="../reset.css"/>
    <style type="text/css">

    </style>
</head>
<body>
<textarea rows="15" cols="55">
    一年前,学校广场上献血.200CC送一副修指甲的用具,400CC送个手表.
    邻班一MM听说了 感觉很幸福,跑过去问护士:”1000CC送什么?” 护士淡定的说:”送个棺材…好笑…” 
</textarea>
<a href="#" unselectable="on ">插入</a>
<script type="text/javascript">
    function logs() {
        var s = '';
        for (var i = 0,aLen = arguments.length; i < aLen; i++) {
            s += arguments[i] + ' ';
        }
        s = s.slice(0, -1);
        if (!window.console) alert(s);
        else
            console.log(s);
    }

   /**
  *
  *
  * @fileOverview   光标处插入文字
  * @author 2kid
  * @email 444212235@qq.com
  * @site 2kid.org
  * @version 9.1
  * @date 2011-08-23
  * Copyright (c) 2011-2012 2kid
  * @example
  *    $('a').click(function(){
        $('textarea').InsertStr({ str:'哈哈哈'});
    });
  */
    (function($){

    	$.fn.InsertStr=function(options){
    		var opt=$.extend({},$.fn.InsertStr.settings,options);
    		return this.each(function(){
    			var	$this=$(this);
    			var	insertStr=new InsertStr(opt);
    				insertStr.init($this);

    		});
    	}
    	var InsertStr=function(options){
    		this.o = options;
    		this.$InsertStr = null;
            this.str=this.o.str;
    	}
    	InsertStr.prototype={
    		init:function(obj){
                var _this=this;
    			this.obj=this.$InsertStr=obj;
                this.insert();

    		},
            insert:function(){
                    //obj是文本框对象
                var obj=$(this.obj).get(0);
                var str=this.str;
                if(document.selection){
                    obj.focus();
                     var r = document.selection.createRange();
                     r.text = str;
                }else if (obj.selectionStart || obj.selectionStart == '0'){
                    var startPos = obj.selectionStart;
                    var endPos = obj.selectionEnd;
                    obj.value = obj.value.substring(0, startPos) + str+
                                          obj.value.substring(endPos, obj.value.length);
                    obj.selectionStart = startPos + str.length;
                    obj.selectionEnd = startPos + str.length;
                 } else {
                    obj.value += str;
                }
                 obj.focus();

            }


    	}



    	$.fn.InsertStr.settings={
            str:"好笑"
    	}
        
    })(jQuery);
  
    $('a').click(function(){
        $('textarea').InsertStr({ str:'哈哈哈'});
    });
</script>
</body>
</html>